/**
 * Created by lzw on 2017/09/16 .
 *  七牛上传图片JS
 *  传入token后执行方法
 */


/*
商品详情-图片上传
*/
function getTokenMessageForUditor() {
    var url = "";
    var qiniupercent = "";
    var uploader = "btn-uploader1";
    var pickfiles = "pickfiles1";
    $.ajax({
        url: token_url,
        type: 'POST',
        data: {},
        cache: false,
        contentType: false,    //不可缺
        processData: false,    //不可缺
        dataType: 'json',
        success: function (data) {
            var obj = data;
            uploaderReadyForUditor(obj.uptoken, url, qiniupercent, uploader, pickfiles);
        }
    });
};

function uploaderReadyForUditor(token, url, qiniupercent, uploader, pickfiles) {
    var uploaderForUditor = Qiniu.uploader({
        runtimes: 'html5,flash,html4',
        browse_button: pickfiles,     //上传按钮的ID
        container: uploader,      //上传按钮的上级元素ID
        drop_element: uploader,
        max_file_size: '1mb',         //最大文件限制
        flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
        dragdrop: true,
        get_new_uptoken: false,
        chunk_size: '4mb',              //分块大小
        //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
        uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
        // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
        domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
        multi_selection: true,         //是否允许同时选择多文件
        filters: {
            mime_types: [               //文件类型过滤，这里限制为图片类型
                {title: "Image files", extensions: "jpg,jpeg,gif,png"}
            ]
        },
        auto_start: true,
        unique_names: true,             //自动生成文件名,如果值为false则保留原文件名上传
        init: {
            'FilesAdded': function (up, files) {
                plupload.each(files, function (file) {
                    // 文件添加进队列后，处理相关的事情
                });
            },
            'BeforeUpload': function (up, file) {
                // 每个文件上传前，处理相关的事情
            },
            'UploadProgress': function (up, file) {
                //文件上传时，处理相关的事情
                /*可能是文件大小
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                */

                //上传进度 class="layui-btn" type="button"
                /*$('#' + qiniupercent).attr('style', 'width:' + file.percent + '%');
                $("#" + qiniupercent).css("background-color", "green");*/

                //console.log(file.percent + "%");
            },
            'UploadComplete': function () {
                //do something
            },
            'FileUploaded': function (up, file, info) {
                //每个文件上传成功后,处理相关的事情
                //其中 info 是文件上传成功后，服务端返回的json，形式如
                //{
                //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                //  "key": "gogopher.jpg"
                //}
                var domain = up.getOption('domain');
                var res = eval('(' + info.response + ')');
                var sourceLink = domain + res.key;//获取上传文件的链接地址

                var $item = $("<div class='edui-image-item'><div class='edui-image-close'></div></div>").append($("<img src='" + sourceLink + "' class='edui-image-pic edui-image-width img-responsive' />"));

                UM.getEditor('container').focus();
                UM.getEditor('container').execCommand('inserthtml', "<img src='" + sourceLink + "' class='edui-image-pic edui-image-width img-responsive' style='width:100%;'/>");
                console.log(sourceLink);

            },
            'Error': function (up, err, errTip) {
                layer.msg(errTip);
            },
            'Key': function (up, file) {
                //当save_key和unique_names设为false时，该方法将被调用
                var key = "";
                $.ajax({
                    url: '/qiniu-token/get-key/',
                    type: 'GET',
                    async: false,//这里应设置为同步的方式
                    success: function (data) {
                        var ext = Qiniu.getFileExtension(file.name);
                        key = data + '.' + ext;
                    },
                    cache: false
                });
                return key;
            }
        }
    });
    uploaderForUditor.start();
}


// 轮播图-上传
function getTokenMessageForUditor2(pic_table) {
    var url = "";
    var qiniupercent = "";
    var uploader = "already";
    var pickfiles = "localUp";
    $.ajax({
        url: token_url,
        type: 'POST',
        data: {},
        cache: false,
        contentType: false,    //不可缺
        processData: false,    //不可缺
        dataType: 'json',
        success: function (data) {
            var obj = data;
            uploaderReadyForUditor2(obj.uptoken, url, qiniupercent, uploader, pickfiles,pic_table);
        }
    });
};

function uploaderReadyForUditor2(token, url, qiniupercent, uploader, pickfiles,pic_table) {
    var uploaderForUditor = Qiniu.uploader({
        runtimes: 'html5,flash,html4',
        browse_button: pickfiles,     //上传按钮的ID
        container: uploader,      //上传按钮的上级元素ID
        drop_element: uploader,
        max_file_size: '1mb',         //最大文件限制
        flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
        dragdrop: false,
        chunk_size: '4mb',              //分块大小
        //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
        uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
        // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
        domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
        multi_selection: true,         //是否允许同时选择多文件
        filters: {
            mime_types: [               //文件类型过滤，这里限制为图片类型
                {title: "Image files", extensions: "jpg,jpeg,gif,png"}
            ]
        },
        auto_start: true,
        unique_names: true,             //自动生成文件名,如果值为false则保留原文件名上传
        init: {
            'FilesAdded': function (up, files) {
                plupload.each(files, function (file) {
                    // 文件添加进队列后，处理相关的事情
                    var nativeFile = file.getNative();
                    var img = new Image();
                    img.src = URL.createObjectURL(nativeFile);
                    img.onload = function() {
                        var width = img.naturalWidth;
                        var height = img.naturalHeight;
                        if(width < 750 || height < 560) {
                            layer.msg('图片分辨率不足750*560，请重新上传');
                            up.removeFile(file);
                            return;
                        } else {
                            // img.src = URL.createObjectURL(nativeFile);
                            // up.start();
                        }
                    }
                });
            },
            'BeforeUpload': function (up, file) {
                // 每个文件上传前，处理相关的事情
                if(imgcount >= 5 ) {
                    layer.msg('您已添加5张，最多添加5张');
                    return false;
                }            
            },
            'UploadProgress': function (up, file) {
                //文件上传时，处理相关的事情

                /*可能是文件大小
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                */

                //上传进度 class="layui-btn" type="button"
                // $('#' + qiniupercent).attr('style', 'width:' + file.percent + '%');
                // $("#" + qiniupercent).css("background-color", "green");

                //console.log(file.percent + "%");
            },
            'UploadComplete': function () {
                //do something
            },
            'FileUploaded': function (up, file, info) {
                //每个文件上传成功后,处理相关的事情,并记录到数据库
                //其中 info 是文件上传成功后，服务端返回的json，形式如
                //{
                //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                //  "key": "gogopher.jpg"
                //}
                var domain = up.getOption('domain');
                var res = eval('(' + info.response + ')');
                var sourceLink = domain + res.key;//获取上传文件的链接地址

                $.ajax({
                    url: record_url,
                    type: 'POST',
                    data: {
                        'imgUrl': sourceLink,
                        'controller': 'product'
                    },
                    cache: false,
                    dataType: 'json',
                    success: function (data) {
                        if (data.code === '1') {
                            var $item = ($('<div class="left"><input type="radio" class="radion" name="imgId" value="' + sourceLink + '"><span id="test" class="layui-icon">စ</span><div style="display: none;"><input type="checkbox" name="imageId" checked value="'+data.image_id+'"><input type="checkbox" checked name="imageUrl" value="'+sourceLink+'"></div><img class="btn-del" src="/public/static/admin/pages/image/del.png" alt="" onclick="deleteIndex(this)"><img class="upPic" src="' + sourceLink + '" name="img" style="width: 150px;height: 112px;"/></div>'));
                            $('.uploaderCon').before($item);
                            tagImg = tagImg + data.image_id + ',';
                            //pic_table.DataTable().ajax.reload();
                            pic_table.DataTable().draw(false);
                            imgcount++;
                        }
                    }
                });

            },
            'Error': function (up, err, errTip) {
                layer.msg(errTip);
            },
        }
    });
    // uploaderForUditor.start(); 
}


//规格模版
var specTypeTemplate1 = stringLines(function () {/*
	<div class="modal-footer">
		<div class="form-group">
			<lable class="col-md-3 control-label"><span class="required"> * </span>规格名称：
			</lable>
			<div class="col-md-9 input-group">
				<input type="text" class="form-control input-medium" name="specType" maxlength="20" placeholder="请输入规格名称">
				<span class="input-group-btn">									        		
	        		<button class="btn btn-info addSepcDetailBtn" type="button">添加规格值</button>
	        		<button class="btn btn-info delSelfBtn1" type="button">删除</button>
	    		</span>
			</div>											
		</div>
	</div>
*/
});
//规格值模版
var specDetailTemplate1 = stringLines(function () {/*
	<div class="form-group">
		<lable class="col-md-3 control-label"><span class="required"> * </span>规格值名称：
		</lable>											
		<div class="col-md-9 input-group">
			<input type="text" class="form-control input-medium" name="specDetails" maxlength="20" placeholder="请输入规格值名称">
			<span class="input-group-btn">
        		<button class="btn btn-info delSelfBtn2" type="button">删除</button>									        		
    		</span>
		</div>
	</div>
*/
});

function trigger_click(str, count, specDetails) {
    var guige = '<div class="modal-footer">' +
        '<div class="form-group">' +
        '<lable class="col-md-3 control-label"><span class="required"> * </span>规格名称：' +
        '</lable>' +
        '<div class="col-md-9 input-group">' +
        '<input type="text" class="form-control input-medium" name="specType" maxlength="20" placeholder="请输入规格名称" value="' + str + '">' +
        '<span class="input-group-btn">	' +
        '<button class="btn btn-info addSepcDetailBtn" type="button">添加规格值</button>' +
        '<button class="btn btn-info delSelfBtn1" type="button">删除</button>' +
        '</span>' +
        '</div>	' +
        '</div>' +
        '</div>';
    var sepcDtl = "";
    var array = new Array(count);
    if (specDetails) {
        array = specDetails.split(',');
    }

    for (var index = 0; index < array.length; index++) {
        // let valuestr=specDetails[''+index+''];
        let valuestr = array[index];

        sepcDtl += '<div class="form-group">' +
            '<lable class="col-md-3 control-label"><span class="required"> * </span>规格值名称：' +
            '</lable>' +
            '<div class="col-md-9 input-group">' +
            '<input type="text" class="form-control input-medium" name="specDetails" maxlength="20" placeholder="请输入规格值名称" value="' + valuestr + '">' +
            '<span class="input-group-btn">' +
            '<button class="btn btn-info delSelfBtn2" type="button">删除</button>' +
            '</span>' +
            '</div>' +
            '</div>'
    }
    guige = guige + sepcDtl;
    $("#modify_spec form > div:last").before(guige);

    //添加规格
    $("#modify_spec form .addSepcDetailBtn:last").click(function () {
        var specDom = $(this).parent().parent().parent().parent();
        specDom.append(specDetailTemplate1);
        $("#modify_spec form .delSelfBtn2").click(function () {
            $(this).parent().parent().parent().remove();
        });
    });

    $("#modify_spec form .delSelfBtn1:last").click(function () {
        $(this).parent().parent().parent().parent().remove();
    });


};

// 商品类型选中
function selectedIsService () {
    var isService = $('.isServiceClass label').find('input:checked').val();
    console.log(isService);
    if(isService == 2){
        // 实物商品
        $('input[name=weight1]').parents('.form-group').show();
    }else{
        $('input[name=weight1]').parents('.form-group').hide();
    }
}

$(function () {

    getTokenMessageForUditor();

    var lm = $("input[name='specClass']:checked").parent("label").index();
    if (lm == -1)
        lm = 0;
    $("input[name='specClass']").eq(lm).prop('checked', 'true');
    $(".specCon").eq(lm).show();

    $(".specClass label").click(function () {
        var ln = $(this).index();
        $(".specCon").eq(ln).show().siblings(".specCon").hide();
    });

    var isPic = $("input[name='isPic']:checked").parent("label").index();
    if (isPic == -1)
        isPic = 0;
    $("input[name='isPic']").eq(isPic).prop('checked', 'true');

    $(".xqClass").eq(isPic).show().siblings(".xqClass").hide();
    ;

    $(".specClass1 label").click(function () {
        var ln = $(this).index();
        $(".xqClass").eq(ln).show().siblings(".xqClass").hide();
    });

    // 初始化商品类型
    selectedIsService();

    // 切换商品类型
    $('.isServiceClass').on('click', 'label', function () {
        selectedIsService();
    });

    /*	//编辑规格
    $("#modifySpecTypeAndDetail").click(function(){
    //	$(".btn_add").hide();
        $("#modify_spec").modal("show");
    //	$("input[name='specTypeName1']").val("");
    });*/

    //规格模版
    var specTypeTemplate = stringLines(function () {/*
		<div class="modal-footer">
			<div class="form-group">
				<lable class="col-md-3 control-label"><span class="required"> * </span>规格名称：
				</lable>
				<div class="col-md-9 input-group">
					<input type="text" class="form-control input-medium" name="specType" maxlength="20" placeholder="请输入规格名称">
					<span class="input-group-btn">									        		
		        		<button class="btn btn-info addSepcDetailBtn" type="button">添加规格值</button>
		        		<button class="btn btn-info delSelfBtn1" type="button">删除</button>
		    		</span>
				</div>											
			</div>
		</div>
	*/
    });
    //规格值模版
    var specDetailTemplate = stringLines(function () {/*
		<div class="form-group">
			<lable class="col-md-3 control-label"><span class="required"> * </span>规格值名称：
			</lable>											
			<div class="col-md-9 input-group">
				<input type="text" class="form-control input-medium" name="specDetails" maxlength="20" placeholder="请输入规格值名称">
				<span class="input-group-btn">
	        		<button class="btn btn-info delSelfBtn2" type="button">删除</button>									        		
	    		</span>
			</div>
		</div>
	*/
    });

    //添加规格类型
    $("#addSpecTypeBtn").click(function () {

        if ($("#modify_spec form .addSepcDetailBtn").length < 3) {
            $("#modify_spec form > div:last").before(specTypeTemplate);

            //添加规格
            $("#modify_spec form .addSepcDetailBtn:last").click(function () {
                var specDom = $(this).parent().parent().parent().parent();
                if (specDom.find(".delSelfBtn2").length < 10) {
                    specDom.append(specDetailTemplate);
                    $("#modify_spec form .delSelfBtn2").click(function () {
                        $(this).parent().parent().parent().remove();
                    });
                } else {
                    $(".modify_spec_help-block").html("一个规格最多10个规格值名称");
                    $(".modify_spec_help-block").css("color", 'red');
                    return;
                }
            });

            $("#modify_spec form .delSelfBtn1:last").click(function () {
                $(this).parent().parent().parent().parent().remove();
            });
        } else {
            $(".modify_spec_help-block").html("最多3个规格名称");
            $(".modify_spec_help-block").css("color", 'red');
            return;
        }

    });


    //完成编辑规格
    $("#modifySpecDetailSure").click(function () {
        var newSpecMetaData = [];
        var isTrue = "";
        var arry1 = [];
        var arry2 = [];
        var isRepeat = "";
        $("#modify_spec input[name='specType']").each(function (m) {
            if (!mdTool.validate($(this).val(), 'require')) {
                $(".modify_spec_help-block").html("请输入规格名称");
                $(".modify_spec_help-block").css("color", 'red');
                if (!isTrue) {
                    isTrue = "请输入规格名称";
                }
                return;
            }
            if (!newSpecMetaData[m]) {
                newSpecMetaData[m] = {};
            }

            if (!arry1[m]) {
                arry1[m] = {};
            }
            arry1[m] = $(this).val();
            newSpecMetaData[m]["specType"] = $(this).val();
            if ($(this).parent().parent().parent().find("input[name='specDetails']").length == 0) {
                $(".modify_spec_help-block").html("缺少规格值名称，请添加规格值");
                $(".modify_spec_help-block").css("color", 'red');
                if (!isTrue) {
                    isTrue = "缺少规格值名称，请添加规格值";
                }
                return;
            }
            $(this).parent().parent().parent().find("input[name='specDetails']").each(function (n) {
                if (!newSpecMetaData[m]["specDetails"]) {
                    newSpecMetaData[m]["specDetails"] = [];
                }
                newSpecMetaData[m]["specDetails"][n] = $(this).val();
                if (!mdTool.validate($(this).val(), 'require')) {
                    $(".modify_spec_help-block").html("请输入规格值名称");
                    $(".modify_spec_help-block").css("color", 'red');
                    if (!isTrue) {
                        isTrue = "请输入规格值名称";
                    }
                    return;
                }

                if (!arry2[n]) {
                    arry2[n] = {};
                }
                arry2[n] = $(this).val();


            })
            if (mdTool.isRepeat(arry2)) {
                if (!isRepeat) {
                    isRepeat = "规格名称值相同，请修改";
                }
                $(".modify_spec_help-block").html("规格名称值相同，请修改");
                $(".modify_spec_help-block").css("color", 'red');
                return false;
            }

        });

        if (isTrue) {
            $(".modify_spec_help-block").html(isTrue);
            $(".modify_spec_help-block").css("color", 'red');
            return;
        } else {
            $(".modify_spec_help-block").html("");
        }
        if (newSpecMetaData.length == 0) {
            $(".modify_spec_help-block").html("请添加规格");
            $(".modify_spec_help-block").css("color", 'red');
            return;
        }
        if ($(this).parent().parent().parent().find("input[name='specDetails']").length <= 0) {
            $(".modify_spec_help-block").html("请添加规格值");
            $(".modify_spec_help-block").css("color", 'red');
            return;
        }


        if (mdTool.isRepeat(arry1)) {
            $(".modify_spec_help-block").html("规格名称相同，请修改");
            $(".modify_spec_help-block").css("color", 'red');
            return;
        }
        if (isRepeat) {
            $(".modify_spec_help-block").html("规格值名称相同，请修改");
            $(".modify_spec_help-block").css("color", 'red');
            return;
        } else {
            $(".modify_spec_help-block").html("");
        }

        $("#modify_spec").modal("hide");

        var _data = $("#modal_new_role").serializeObject();
        var specDetailsList = $("input[name='specDetails']").val();
        // var list= JSON.parse(specDetailsList);
        console.log(newSpecMetaData);

        //生成规格组合表格
        if (newSpecMetaData.length > 0) {
            var specHeadBuf = "<tr>";
            for (var i = 0; i < newSpecMetaData.length; i++) {
                specHeadBuf += '<th><input type="hidden" name="specType' + (Number(i) + 1) + '" value="' + newSpecMetaData[i]['specType'] + '">';
                specHeadBuf += newSpecMetaData[i]["specType"];
                specHeadBuf += "</th>";
            }
            specHeadBuf += "<th>库存数量</th><th>限购数量</th><th>现价(元)</th><th>会员价(元)</th><th>拼团价(元)</th><th>兑换积分</th><th>重量(kg)</th>";
            specHeadBuf += '<input type="hidden" name="spec" value=' + JSON.stringify(newSpecMetaData) + ' />';
            specHeadBuf += "</tr>";

            var specBodyBuf = "";
            //生成行数据
            var specIds = "";
            var buildBodyRowFunc = function () {
                var specRowBuf = "<tr>";
                for (var x in arguments) {
                    specRowBuf += '<td><input type="hidden" name="specDetails' + (Number(x) + 1) + '" value="' + arguments[x] + '">';
                    specRowBuf += arguments[x];
                    specRowBuf += "</td>";
                    specIds += specIds
                }
                ;
                specRowBuf += stringLines(function () {/*
					<input type="hidden" name="spec_id">
					<td>
						<input type="text" class="form-control input-xsmall" name="storeCount" maxlength="8">
					</td>
					<td>
						<input type="text" class="form-control input-xsmall" name="limitCount" maxlength="8">
					</td>
					<td>
						<input type="number" class="form-control input-xsmall" name="currentPrice" maxlength="8" >
					</td>
					<td>
						<input type="number" class="form-control input-xsmall" name="memberPrice" maxlength="8" >
					</td>
                    <td>
                        <input type="number" class="form-control input-xsmall" name="groupPrice" maxlength="8" >
                    </td>
                    <td>
                        <input type="number" class="form-control input-xsmall" name="integralPrice" maxlength="8" onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" >
                    </td>
                    <td>
                        <input type="number" class="form-control input-xsmall" name="weight" maxlength="8" >
                    </td>		
				*/
                });
                specRowBuf += "</tr>";
                return specRowBuf;
            }
            for (var spec1 in newSpecMetaData[0]["specDetails"]) {
                if (newSpecMetaData.length > 1) {
                    for (var spec2 in newSpecMetaData[1]["specDetails"]) {
                        if (newSpecMetaData.length == 3) {
                            for (var spec3 in newSpecMetaData[2]["specDetails"]) {
                                specBodyBuf += buildBodyRowFunc(newSpecMetaData[0]["specDetails"][spec1],
                                    newSpecMetaData[1]["specDetails"][spec2],
                                    newSpecMetaData[2]["specDetails"][spec3]);
                            }
                        } else {
                            specBodyBuf += buildBodyRowFunc(newSpecMetaData[0]["specDetails"][spec1],
                                newSpecMetaData[1]["specDetails"][spec2]);
                        }
                    }
                } else {
                    specBodyBuf += buildBodyRowFunc(newSpecMetaData[0]["specDetails"][spec1]);
                }
            }

            //将DOM写到页面
            $("#table_spec thead").html(specHeadBuf);
            $("#table_spec tbody").html(specBodyBuf);
            var specDetails1s = _data.specDetails1;
            var length;
            if (_data.specType3) {
                length = 3;
            } else if (_data.specType2) {
                length = 2;
            } else if (_data.specType1) {
                length = 1;
            }
            var specDetails2s = _data.specDetails2;
            var specDetails3s = _data.specDetails3;
            var spec_ids = _data.spec_id;
            var storeCounts = _data.storeCount;
            var limitCounts = _data.limitCount;
            var currentPrice = _data.currentPrice;
            var memberPrice = _data.memberPrice;
            var groupPrice = _data.groupPrice;
            var integralPrice = _data.integralPrice;
            var weight = _data.weight;
            var specType1 = $("#table_spec tbody tr:first").find("input[name='specType1']").val();
            var specType2 = $("#table_spec tbody tr:first").find("input[name='specType2']").val();
            var specType3 = $("#table_spec tbody tr:first").find("input[name='specType3']").val();

            $("#table_spec tbody").find("tr").each(function (i) {
                var specDetails1 = $(this).find("input[name='specDetails1']").val();
                var specDetails2 = $(this).find("input[name='specDetails2']").val();
                var specDetails3 = $(this).find("input[name='specDetails3']").val();
                for (var a in specDetails1s) {
                    if (length === 1) {
                        if (specDetails1s[a] == specDetails1 && !specType2) {
                            $(this).find("input[name='spec_id']").val(spec_ids[a])
                            $(this).find("input[name='storeCount']").val(storeCounts[a])
                            $(this).find("input[name='limitCount']").val(limitCounts[a])
                            $(this).find("input[name='currentPrice']").val(currentPrice[a])
                            $(this).find("input[name='memberPrice']").val(memberPrice[a])
                            $(this).find("input[name='groupPrice']").val(groupPrice[a])
                            $(this).find("input[name='integralPrice']").val(integralPrice[a])
                            $(this).find("input[name='weight']").val(weight[a])
                        }
                    }
                    if (length === 2) {
                        if (specDetails1s[a] == specDetails1 && specDetails2s[a] == specDetails2 && !specType3) {
                            $(this).find("input[name='spec_id']").val(spec_ids[a])
                            $(this).find("input[name='storeCount']").val(storeCounts[a])
                            $(this).find("input[name='limitCount']").val(limitCounts[a])
                            $(this).find("input[name='currentPrice']").val(currentPrice[a])
                            $(this).find("input[name='memberPrice']").val(memberPrice[a])
                            $(this).find("input[name='groupPrice']").val(groupPrice[a])
                            $(this).find("input[name='integralPrice']").val(integralPrice[a])
                            $(this).find("input[name='weight']").val(weight[a])
                        }
                    } else if (length === 3) {
                        if (specDetails1s[a] == specDetails1 && specDetails2s[a] == specDetails2 && specDetails3s[a] == specDetails3) {
                            $(this).find("input[name='spec_id']").val(spec_ids[a])
                            $(this).find("input[name='storeCount']").val(storeCounts[a])
                            $(this).find("input[name='limitCount']").val(limitCounts[a])
                            $(this).find("input[name='currentPrice']").val(currentPrice[a])
                            $(this).find("input[name='memberPrice']").val(memberPrice[a])
                            $(this).find("input[name='groupPrice']").val(groupPrice[a])
                            $(this).find("input[name='integralPrice']").val(integralPrice[a])
                            $(this).find("input[name='weight']").val(weight[a])
                        }
                    }
                }

            })
        }

    });


    $(".addSpecDetail").on("click", function (e) {
        var spec = $("#form_spec_new input[name='specDetails']").val();
        $("#form_spec_new .spec_list").append('<label >' + spec + '<span class="glyphicon glyphicon-remove"></span></label>');

    })
    //修改规则
    $(".modifySpecDetail").on("click", function (e) {
        var spec = $("#form_spec_modify input[name='specDetails']").val();
        $("#form_spec_modify .spec_list_edit").append('<label >' + spec + '<span class="glyphicon glyphicon-remove"></span></label>');

    })

    $(".isStoreCheck").on("click", function (e) {
        if ($(this).is(':checked')) {
        } else {
        }
    });
    // 确定添加
    $("#save").click(function () {
        var _data = $("#modal_new_role").serializeObject();
        var typeId = _data.typeId + "";
        var imgUrl = "";
        var imgUrl = _data.imgId;

        var _id = _data.id;

        var pro_detail = UM.getEditor('container').getContent();
        if (!mdTool.validate(_data.title, 'require')) {
            layer.msg('请填写商品名称');
            $('#modal_new_role').find('input[name="title"]').focus();
            return;
        }
        //循环多个详情图片
        var imageId = _data.imageId;
        if (imageId instanceof Array) {   //处理图片数组
            var length = imageId.length;
            arrayImg = new Array(length);
            for (var i = 0; i < length; i++) {
                simg = {"imageId": _data.imageId[i], "imageUrl": _data.imageUrl[i]};
                arrayImg[i] = simg;
            }
        } else {  //只选了一张图片
            arrayImg = new Array(1);
            arrayImg[0] = !imageId ? new Array() : {"imageId": _data.imageId, "imageUrl": _data.imageUrl};
        }

        if (!mdTool.validate(_data.typeId, 'require')) {
            layer.msg('请选择商品分类');
            return;
        }
        if (!imgUrl) {
            layer.msg('请选择主图');
            return;
        }

        if (_data.specClass == '1') {
            if ( !mdTool.validate(_data.currentPrice1, 'require') || !mdTool.validate(_data.memberPrice1, 'require')  ) {
                layer.msg('所有价格不能为空');
                return;
            }
            if ( Number(_data.currentPrice1) < 0 || Number(_data.memberPrice1) < 0 ) {
                layer.msg('价格必须为正整数');
                return;
            } else if ( !mdTool.validate(_data.currentPrice1, 'two') || !mdTool.validate(_data.memberPrice1, 'two')) {
                layer.msg('价格最多只能两位小数');
                return;
            }
            if(parseFloat(_data.memberPrice1) >= parseFloat(_data.currentPrice1)) {
               layer.msg('会员价必须小于现价');
               $('#modal_new_role').find('input[name="memberPrice1"]').focus();
                return; 
            }
            if(_data.groupPrice1 && (_data.groupPrice1.length > 1 || _data.groupPrice1 != 0)) {  //填写了拼团价
                if (!mdTool.validate(_data.groupPrice1, 'znum')) {
                    layer.msg('请输入正确的商品拼团价');
                    $('#modal_new_role').find('input[name="groupPrice1"]').focus();
                    return;
                }
                if ( !mdTool.validate(_data.groupPrice1, 'two')) {
                    layer.msg('拼团价最多只能两位小数');
                    $('#modal_new_role').find('input[name="groupPrice1"]').focus();
                    return;
                }
            }
            if(_data.isStore==undefined) {  //限制库存，检查库存数量是否填写
                if ( !mdTool.validate(_data.storeCount1, 'num')) {
                    layer.msg('请输入库存数量');
                    $('#modal_new_role').find('input[name="storeCount1"]').focus();
                    return;
                }
            } else {
                _data.storeCount1 = 0;
            }         
            
            if(_data.isService == 2) {  //实物商品判断重量是否填写
                if (!mdTool.validate(_data.weight1, 'znum')) {
                    layer.msg('请输入正确的商品重量');
                    $('#modal_new_role').find('input[name="weight1"]').focus();
                    return;
                }
                if (!mdTool.validate(_data.weight1, 'three')) {
                    layer.msg('重量最多只能三位小数');
                    $('#modal_new_role').find('input[name="weight1"]').focus();
                    return;
                }
            }

        } else if (_data.specClass == '2') {

            var specDetails1s = _data.specDetails1;
            var array;
            if (!specDetails1s) {
                layer.msg('请添加规格');
                return;
            }
            if($(".isStoreCheck").is(':checked')) {
                var isStore = 0;  //无限制，不计算库存
            } else {
                var isStore = 1;  //计算库存
            }
            if (specDetails1s instanceof Array) {
                var length = specDetails1s.length;
                array = new Array(length);
                for (var i = 0; i < length; i++) {
                    if($(".isStoreCheck").is(':checked') == false) {
                        if (!mdTool.validate(_data.storeCount[i], 'num')) {
                            layer.msg('请输入正确的库存数量');
                            return;
                        }
                    } else {
                        _data.storeCount[i] = 0;
                    }

                    if (!mdTool.validate(_data.currentPrice[i], 'require') || !mdTool.validate(_data.memberPrice[i], 'require')) {
                        layer.msg('请填写规格价格');
                        return;
                    }
                    if (Number(_data.currentPrice[i]) < 0 || Number(_data.memberPrice[i]) < 0 ) {
                        layer.msg('价格不能小于0');
                        return;
                    } else if (!mdTool.validate(_data.currentPrice[i], 'two') || !mdTool.validate(_data.memberPrice[i], 'two')) {
                        layer.msg('价格最多只能两位小数');
                        return;
                    }
                    if(parseFloat(_data.memberPrice[i]) >= parseFloat(_data.currentPrice[i])) {  //会员价不能大于现价
                        layer.msg('会员价必须小于现价');
                        return;
                    }

                    if(_data.isService == 2) {  //实物商品判断重量是否填写   
                        if (!mdTool.validate(_data.weight[i], 'require')) {
                            layer.msg('请输入商品重量');
                            return;
                        }
                        if (!mdTool.validate(_data.weight[i], 'three')) {
                            layer.msg('重量最多只能三位小数');
                            return;
                        }
                    }

                    var productSpec;
                    if (_data.specDetails3) {
                        productSpec = {
                            "id": _data.spec_id[i],
                            "specDetails1": _data.specDetails1[i],
                            "specDetails2": _data.specDetails2[i],
                            "specDetails3": _data.specDetails3[i],
                            "storeCount": _data.storeCount[i],
                            "limitCount": _data.limitCount[i],
                            "currentPrice": _data.currentPrice[i],
                            "memberPrice": _data.memberPrice[i],
                            "groupPrice": _data.groupPrice[i] > 0 ? _data.groupPrice[i] : 0,
                            "integralPrice": _data.integralPrice[i],
                            "isStore": isStore,
                            'weight':_data.weight[i]
                        };
                        array[i] = productSpec;
                    } else if (_data.specDetails2) {
                        productSpec = {
                            "id": _data.spec_id[i],
                            "specDetails1": _data.specDetails1[i],
                            "specDetails2": _data.specDetails2[i],
                            "storeCount": _data.storeCount[i],
                            "limitCount": _data.limitCount[i],
                            "currentPrice": _data.currentPrice[i],
                            "memberPrice": _data.memberPrice[i],
                            "groupPrice": _data.groupPrice[i] > 0 ? _data.groupPrice[i] : 0,
                            "integralPrice": _data.integralPrice[i],
                            "isStore": isStore,
                            'weight':_data.weight[i]
                        };
                        array[i] = productSpec;
                    } else {
                        productSpec = {
                            "id": _data.spec_id[i],
                            "specDetails1": _data.specDetails1[i],
                            "storeCount": _data.storeCount[i],
                            "limitCount": _data.limitCount[i],
                            "currentPrice": _data.currentPrice[i],
                            "memberPrice": _data.memberPrice[i],
                            "groupPrice": _data.groupPrice[i] > 0 ? _data.groupPrice[i] : 0,
                            "integralPrice": _data.integralPrice[i],
                            "isStore": isStore,
                            'weight':_data.weight[i]
                        };
                        array[i] = productSpec;
                    }

                }

            } else {
                if($(".isStoreCheck").is(':checked') == false) {   //限制库存
                    if (!mdTool.validate(_data.storeCount, 'num')) {
                        if (_data.storeCount != '0') {
                            layer.msg('请输入正确的库存数量');
                            return;
                        }
                    }
                }else{
                    _data.storeCount = 0;
                }
                if (!mdTool.validate(_data.limitCount, 'num')) {
                    layer.msg('请输入正确的限购数量');
                    return;

                }

                if (!mdTool.validate(_data.currentPrice, 'require') || !mdTool.validate(_data.memberPrice, 'require')) {
                    layer.msg('价格不能为空');
                    return;
                }
                if (Number(_data.price) < 0 || Number(_data.currentPrice) < 0 || Number(_data.memberPrice) < 0 ) {
                    layer.msg('价格不能小于0');
                    return;
                } else if ( !mdTool.validate(_data.currentPrice, 'two') || !mdTool.validate(_data.memberPrice, 'two')) {
                    layer.msg('价格最多只能两位小数');
                    return;
                }
                if(_data.isService == 2) {  //实物商品判断重量是否填写 
                    if (!mdTool.validate(_data.weight, 'require')) {
                        layer.msg('请输入商品重量');
                        return;
                    }
                    if (!mdTool.validate(_data.weight, 'three')) {
                        layer.msg('重量最多只能三位小数');
                        return;
                    }
                } else {
                    _data.weight = '';
                }

                array = [{
                    "id": _data.spec_id,
                    "specDetails1": _data.specDetails1,
                    "specDetails2": _data.specDetails2,
                    "specDetails3": _data.specDetails3,
                    "storeCount": _data.storeCount,
                    "limitCount": _data.limitCount,
                    "currentPrice": _data.currentPrice,
                    "memberPrice": _data.memberPrice,
                    "groupPrice": _data.groupPrice >0 ? _data.groupPrice : 0,
                    "integralPrice": _data.integralPrice,
                    "isStore": isStore,
                    'weight':_data.weight
                }];
            }
        }


        if (!mdTool.validate(pro_detail.trim(), 'require')) {
            layer.msg('请填写商品详情');
            return;
        }
        var lenth = mdTool.sumBytes(pro_detail);
        if (lenth > 60534) {//64K
            layer.msg('您输入的商品详情已超过最大范围,请修改后保存');
            return;
        }
        else {
            var param = {
                "product": {
                    "title": _data.title,
                    "id": _id,
                    "typeId": _data.typeId,
                    "imgUrl": imgUrl,
                    "isActive": _data.isActive,
                    "weight": _data.weight1 * 1000,
                    "price": _data.price * 100,
                    "currentPrice": _data.currentPrice1 * 100,
                    "memberPrice": _data.memberPrice1 * 100,
                    "groupPrice": _data.groupPrice1 * 100,
                    "integralPrice": _data.integralPrice1,
                    "storeCount": _data.storeCount1,
                    "limitCount": _data.limitCount1,
                    "specClass": _data.specClass,
                    "specType1": _data.specType1,
                    "specType2": _data.specType2,
                    "specType3": _data.specType3,
                    "isPic": _data.isPic,
                    "spec": _data.spec,
                    "isStore" : _data.isStore,
                    "isService": _data.isService,
                    "qrCode": _data.qrCode
                }, "detail": pro_detail, "productSpec": JSON.stringify(array), "ProductDtlImg": JSON.stringify(arrayImg)
            }
            var _type = _id == null || _id == '' ? "post" : "put";
            $("#save").prop("disabled", true);
            $.ajax({
                url: edit_url,
                type: _type,
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(param),
            }).done(function (data) {
                if (data.status === '1') {// 正确
                    layer.msg('保存成功');
                    window.location.href = index_url;
                } else if (data.status === '2') {// 错误
                    $('#modal_new_role .help-block').html(data.msg); // 返回错误信息
                    $("#save").prop("disabled", false);
                }
            }).fail(function (data) {
                var msg = 'data.responseJSON.message';
                layer.msg(msg + "格式不正确，请修改");
                $("#save").prop("disabled", false);

            });
        }
    });

    $(".add_type").on("click", function () {
        $("#modal_new_type").find('input[name=name]').val('');
        $("#modal_new_type").modal('show');
    });


    //新增分类
    $(".btn_newType").click(function () {
        var _data = $("#form_role_new").serializeObject();
        var name = $("#modal_new_type input[name='name']").val();
        var order = $("#modal_new_type input[name='orderNo']").val();
        if (!mdTool.validate(name, 'require')) {
            layer.msg("请输入分类名称");
            return;
        } else {
            var param = {"name": name, "orderNo": order};
            $.ajax({
                url: type_url,
                type: "POST",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(param),
            }).done(function (data) {
                if (data.code === '1') {
                    $("#checkbox_upd").append('<label class="btn btn-default checkbox-inline margin-bottom pro_type1"><input type="checkbox" name="typeId" value="' + data.id + '" style="position: relative !important; padding: 0;margin: 0;">' + data.name + '</label>');
                    $('#modal_new_type').modal('hide');
                    $(".pro_type1").click(function () {
                        if ($(this).is(".active")) {
                            $(this).removeClass("active");
                            $(this).find("input[type='checkbox']").prop("checked", false);
                            return false;
                        } else {
                            $(this).addClass("active");
                            $(this).find("input[type='checkbox']").prop("checked", true);
                            return false;
                        }
                    });
                } else if (data.code === '2') {
                    layer.msg(data.message);
                }
            })
        }
    });


    $(".addSpecDetailSure").on("click", function (e) {
        $("#add_spec").modal("hide");
        var spec = $("#form_spec_new input[name='specType']").val();
        var specList = new Array();

        var spec_List = "";
        $("#form_spec_new .spec_list label").each(function (i) {
            specList[i] = "<label >" + $("#form_spec_new .spec_list label").eq(i).text() + "</label>";
            spec_List = spec_List + "  <label >" + $("#form_spec_new .spec_list label").eq(i).text() + "</label>";
        })
        var spec_list = $("#form_spec_new .spec_list").text();

        var rowTem = '<tr class="tr_' + i + '"  style=" background: #DDDDDD;">'
            + '<td style="width:80%">' + spec + '</td>'
            + '<td ><div class="pull-right" ><a href="javascript:void(0) " class="spec_modify"  >编辑</a> <a href="javascript:void(0) " class="spec_delete"   >删除</a></div></td>'
            + '</tr>';


        var rowTem1 = '<tr >'
            + '<td style="width:80%">' + spec_List + '</td>'
            + '<td></td>'
            + '</tr>';
        $("#table_spec1 tbody:last").append(rowTem);
        $("#table_spec1 tbody:last").append(rowTem1);
        i++

        //定义一个值传到编辑页面
        var isEdit = "tr_1";
        $(".spec_modify").on("click", function (e) {
            $(this).parent().parent().parent().attr("id", "tr_1");
            $("#modify_spec").modal("show");
            $("input[name='editSpec']").val(isEdit);
            var specType = $(this).parent().parent().parent().find("td").eq(0).html();
            $("#form_spec_modify .spec_list").val('');
            $(this).parent().parent().parent().next("tr").find("td").eq(0).find("label").each(function (i) {
                $("#form_spec_modify .spec_list").append('<label >' + $(this).html() + '<span class="glyphicon glyphicon-remove"></span></label>');

            });

            $("#modify_spec input[name='specType']").val(specType)
        })

        $(".spec_delete").on("click", function (e) {
            $(this).parent().parent().parent().next("tr").remove();
            $(this).parent().parent().parent().remove();
        })
    });

    var specmodifyList = "";
    $(".modifySpecDetailSure").on("click", function (e) {
        $("#add_spec").modal("hide");
        //找到编辑的行
        $("#table_spec1 tbody:last").find("tr").each(function () {

            if (typeof($(this).attr("id")) != "undefined") {
                if ($(this).attr("id") == "tr_1") { //替换当前行的值
                    //  alert($(this).next("tr").html());
                    $(this).find("td").eq(0).html($("#modify_spec input[name='specType']").val());
                    //添加label
                    $("#form_spec_modify .spec_list_edit label").each(function (i) {
                        specmodifyList = "<label >" + $("#form_spec_modify .spec_list_edit label").eq(i).text() + "</label>";
                        specmodifyList = specmodifyList + "<label >" + $("#form_spec_modify .spec_list_edit label").eq(i).text() + "</label>";
                    })
                    $(this).next("tr").html(specmodifyList);
                    //
                    $("input[name='editSpec']").val("");
                }

            }
        });
    });
    $(".btn_add_con .btn_cancle_role").click(function () {
        $(".btn_add").show();
        $(".btn_add_con").hide();
    });


    //删除规格值
    $(".spec_list").on("click", "label .glyphicon", function () {
        var _specTypeName = $(this).parent("label").text();
        var isDel = true;
        /*	$.ajax({
                url: '/a/wxconf/group/delSpecType',
                type: 'delete',
               async: false,//这里应设置为同步的方式
                data: JSON.stringify({specTypeName:_specTypeName}),
                dataType : 'json',
                contentType : "application/json; charset=utf-8",
                success: function (data) {
                    if(data.status=='1'){
                        isDel = true;
                    }else{
                        alert(data.message);
                    }
                }
            });*/
        if (isDel == true) {
            $(this).parent("label").remove();
        }
    });

    //下拉规则
    $("#selectSpecType").on("change", function () {
        var option = "<option th:value='" + $(this).val() + "'>" + $(this).val() + "</option>";
        $("#selectSpecType").html(option);
    });
    $("#selectSpecType").on("click", function () {
        //	var opt = "";
        $.ajax({
            url: '/a/wxconf/group/selSpecType',
            type: 'get',
            async: false,//这里应设置为同步的方式
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                if (data.status == '1') {
                    if (data.data.length > 0) {
                        $("#selectSpecType").empty();
                        for (var i = 0; i < data.data.length; i++) {
                            var str = "<option th:value='" + data.data[i].specTypeName + "'>" + data.data[i].specTypeName + "</option>";
                            $("#selectSpecType").append(str);
                        }
                    }

                } else {
                    layer.msg(data.message);
                }
            }
        });
    });


    $(".btn_add2 .btn_save_role").click(function () {
        $(".btn_add2").hide();
        $(".btn_add_con2").show();
        $(".spec_list2").hide();
        $("#sst").show();

    });


    $(".btn_add_con2 .btn_cancle_role").click(function () {
        $(".btn_add2").show();
        $(".btn_add_con2").hide();
    });

    $(".btn_add_con2 .btn_save_role").click(function () {
        //获取选中的规格，没选提示它
        $("#selst").html($("#selectSpecType").val());
        //$(".btn_add2").show();
        $(".spec_list2").show();
        $(".spec_list2 label").hide();
        $(".spec_list2 #selst").show();
        $("#sst").hide();
        //隐藏保存和取消
        $(".btn_add_con2 .btn").hide();
    });

    $("#selst").click(function () {
        $(".btn_add2").hide();
        $(".btn_add_con2").show();
        $("#sst").show();
        $(".spec_list2").hide();
        $(".btn_add_con2 .btn").show();
        $("#selst").html("");
    });

    $("#table_spec #tb1").on('click', '.btn_cancle_spec', function () {
        $(this).parent().parent().remove();
    });
});


//图片控件 --begin
var pic_table = $('#pic_table');
var tagImg = $('.upPicCon .storeimg').find('input[name="tagImg"]').val();
imgcount = tagImg.split(',').length;
tagImg += ',';
pic_table.dataTable({
    "processing": true,
    serverSide: false,
    destroy:false,  
    "ajax": {
        url:layer_img,
    },
    "autoWidth": false,
    "columns": [
        {
            "width": "10%",
            "data": "imgUrl",
            "render": function(data, type, row, meta) {
                if(tagImg.indexOf(row.id+',') !== -1) {
                    return '<div class="left image"><label for="" class="active"><img class="select" src="/public/static/admin/pages/image/yes.png"></label>'+
                    '<div style="display: none;"><input type="checkbox" name="imageId" checked value="'+row.id+'"><input type="checkbox" checked name="imageUrl" value="'+data+'"></div>'+
                    '<img class="upPicList" src="'+data+'" /></div>';
                } else {
                    return '<div class="left image"><label for="" class="active" style="display: none"><img class="select" src="/public/static/admin/pages/image/yes.png"></label>'+
                    '<div style="display: none;"><input type="checkbox" name="imageId" value="'+row.id+'"><input type="checkbox" name="imageUrl" value="'+data+'"></div>'+
                    '<img class="upPicList" src="'+data+'" /></div>';
                }
            }
        },
    ],
    "language": {
        url: '/public/static/assets/pages/Chinese.json'
    },
    "pageLength": 18,
    "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
        "<t>" +
        "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
    "fnInitComplete": function() {}
});

pic_table.on('click', '.upPicList', function(event) {
    console.log('click');
    $(this).parent().find(".active").toggle();
    console.log('原始' + imgcount);
    var id = $(this).parent().find("input[name='imageId']").val();   //图片id
    var url = $(this).attr('src');   //图片地址

    var img = new Image();
    img.src = url;
    if(img.width < 750 || img.height < 560) {
        layer.msg('图片尺寸不合理，请重新选择');
        $(this).parent().find(".active").toggle();
        $(this).parent().find("input").prop("checked", false);
        return;
    }

    if ($(this).parent().find(".active").is(':visible')) {  //选中,添加
        if (imgcount >= 5) {
            layer.msg('最多添加5张图片');
            $(this).parent().find('.active').hide();
            return;
        }
        imgcount++;
        console.log('增加' + imgcount);
        $(this).parent().find("input").prop("checked", true);
        var $item = ($('<div class="left"><input type="radio" class="radion" name="imgId" value="' + url + '"><span id="test" class="layui-icon">စ</span><div style="display: none;"><input type="checkbox" name="imageId" checked value="'+id+'"><input type="checkbox" checked name="imageUrl" value="'+url+'"></div><img class="btn-del" src="/public/static/admin/pages/image/del.png" alt="" onclick="deleteIndex(this)"><img class="upPic" src="' + url + '" name="img" style="width: 150px;height: 112px;"/></div>'));
        $('.uploaderCon').before($item);

    } else {
        if (imgcount <= 1) {
            layer.msg('最后一张图片，不能删除');
            $(this).parent().find('.active').show();
            return;
        }
        imgcount--;
        //console.log('减少' + imgcount);
        $(this).parent().find("input").removeAttr("checked");
         $(".storeimg .left img[name='img']").each(function (i) {
            var imgsrc = $(this).attr('src');
            if(imgsrc.indexOf('?') > 0) {
                imgsrc = imgsrc.slice(0,imgsrc.indexOf('?'));
            }
            if (imgsrc == url) {  // 删除图片
                $(this).parent().remove();
            }
        });
    }
});

getTokenMessageForUditor2(pic_table);

//关闭弹窗前检查数量
$('#uploaderBox .close-check').click(function(){
    if(imgcount > 5) {
        layer.msg('最多添加5张图片，请去掉多余图片');
        return false;
    } else {
        $('.modal').hide();
    }
});

//图片控件 --end

//图片删除
function deleteIndex(e) {  //删除已选中图片
    if(imgcount <= 1) {  //检测图片数量
        layer.msg('最后一张图片，不能删除');
        return;
    }
    if($(e).parent().find('input[name="imgId"]').is(':checked')) {  //检测是否为主图，若是，不允许删除
        layer.msg('主图不能被删除，若想删除，请选择其他图片为主图');
        return;
    }
    imgcount--;

    var id = $(e).parent().find('input[name="imageId"]').val();
    var nTrs=$('#pic_table').dataTable().fnGetNodes();  //表格中所有页中的项
    for(var i = 0; i < nTrs.length; i++){
       if($(nTrs[i]).find('input[name="imageId"]').val() == id){  //去除图片组件中的选中样式
            $(nTrs[i]).find('input[name="imageId"]').removeAttr('checked');
            $(nTrs[i]).find('input[name="imageUrl"]').removeAttr('checked');
            $(nTrs[i]).find('label.active').hide();
        }
   }
    $(e).parent().remove();  //删除页面显示元素

}

var i = 0;

function addRow() {
    if ($("#selst").html() == "") {
        layer.msg("请先选择规格!");
        return;
    }
    var str = '<tr class="tr_' + i + '">'
        + '<td><input type="text" class="form-control" name="specValue"  maxlength = "12" /></td>'
        + '<td><input type="text" class="form-control" name="sgPrice" maxlength = "12" /></td>'
        + '<td><input type="text" class="form-control"  name="proPrice" maxlength = "5"></td>'
        + '<td><button type="button" class="btn btn_cancle_spec">取消</button></td>'
        + '</tr>';
    $("#table_spec #tb1:last").append(str);
    //getTokenMessage();
    i++
};

$(".pro_type input[type='checkbox']").each(function () {
    if ($(this).is(":checked")) {
        $(this).parent("label").addClass("active");
    }
});
$(".pro_type label").click(function () {
    if ($(this).is(".active")) {
        $(this).removeClass("active");
        $(this).find("input[type='checkbox']").prop("checked", false);
        return false;
    } else {
        $(this).addClass("active");
        $(this).find("input[type='checkbox']").prop("checked", true);
        return false;
    }
});


if ($("input[name='specClass']:checked").val() == "2") {//多规格
    var _id = $("input[name='id']").val();

    //启用
    $.ajax({
        url: spec_url,
        type: 'post',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({id: _id}),
    }).done(function (data) {
        if (data.status === '1') {
            var st1 = $("input[name='specType1s']").val();
            var st2 = $("input[name='specType2s']").val();
            var st3 = $("input[name='specType3s']").val();
            var list = JSON.parse($("input[name='list']").val());
            var trth = "<tr>";
            var count = 0;
            if (st1 != "") {
                trth += '<th><input type="hidden"  name="specType1" value="' + st1 + '" maxlength="8">' + st1 + '</th>';
                count = count + 1;
            }
            if (st2 != "") {
                trth += '<th><input type="hidden"  name="specType2" value="' + st2 + '" maxlength="8">' + st2 + '</th>';
                count = count + 1;
            }
            if (st3 != "") {
                trth += '<th><input type="hidden"  name="specType3" value="' + st3 + '" maxlength="8">' + st3 + '</th>';
                count = count + 1;
            }
            trth += "<th>库存数量</th><th>限购数量</th><th>现价(元)</th><th>会员价(元)</th><th>拼团价(元)</th><th>兑换积分</th><th>重量(kg)</th></tr>";
            var trtr = "<tr>";

            if (data.data != null) {
                var specDetails = data.data;
                for (var i = 0; i < specDetails.length; i++) {
                    if (count == 1) {
                        trtr += '<td><input type="hidden"  name="specDetails1" value="' + specDetails[i].specDetails1 + '" maxlength="8">' + specDetails[i].specDetails1 + '</td>';
                    } else if (count == 2) {
                        trtr += '<td><input type="hidden"  name="specDetails1" value="' + specDetails[i].specDetails1 + '" maxlength="8">' + specDetails[i].specDetails1 + '</td>';
                        trtr += '<td><input type="hidden"  name="specDetails2" value="' + specDetails[i].specDetails2 + '" maxlength="8">' + specDetails[i].specDetails2 + '</td>';
                    } else if (count == 3) {
                        trtr += '<td><input type="hidden"  name="specDetails1" value="' + specDetails[i].specDetails1 + '" maxlength="8">' + specDetails[i].specDetails1 + '</td>';
                        trtr += '<td><input type="hidden"  name="specDetails2" value="' + specDetails[i].specDetails2 + '" maxlength="8">' + specDetails[i].specDetails2 + '</td>';
                        trtr += '<td><input type="hidden"  name="specDetails3" value="' + specDetails[i].specDetails3 + '" maxlength="8">' + specDetails[i].specDetails3 + '</td>';
                    }
                    trtr += '<input type="hidden" name="spec_id" value="' + specDetails[i].id + '" />'
                    trtr += '<td><input type="text" class="form-control input-xsmall" name="storeCount" value="' + specDetails[i].storeCount + '" maxlength="8"></td>';
                    trtr += '<td><input type="text" class="form-control input-xsmall" name="limitCount" value="' + specDetails[i].limitCount + '" maxlength="8"></td>';
                    trtr += '<td><input type="number" class="form-control input-xsmall" name="currentPrice" value="' + specDetails[i].currentPrice / 100 + '" maxlength="8"></td>';
                    trtr += '<td><input type="number" class="form-control input-xsmall" name="memberPrice" value="' + specDetails[i].memberPrice / 100 + '" maxlength="8"></td>';
                    trtr += '<td><input type="number" class="form-control input-xsmall" name="groupPrice" value="' + specDetails[i].groupPrice / 100 + '" maxlength="8"></td>';
                    trtr += '<td><input type="number" class="form-control input-xsmall" name="integralPrice" value="' + specDetails[i].integralPrice + '" maxlength="8"></td>';
                    trtr += '<td><input type="number" class="form-control input-xsmall" name="weight" value="' + specDetails[i].weight / 1000 + '" maxlength="8"></td></tr>';
                }

                if (st1 != "") {
                    $("#addSpecTypeBtn").trigger("click");
                }
                if (st2 != "") {
                    $("#addSpecTypeBtn").trigger("click");
                }
                if (st3 != "") {
                    $("#addSpecTypeBtn").trigger("click");
                }
            }
            $("#table_spec tbody").append(trth);
            $("#table_spec tbody:last").append(trtr);

            $(".sepcdtlUpdate").on("click", function () {
                let oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
                let _id = oData_arr[0].id;

            });

            $("#modify_spec input[name='specType']").each(function (m) {
                $(this).val(list[m]["specType"]);
                var specDetails = list[m]["specDetails"];
                for (var j = 0; j < specDetails.length; j++) {
                    $(this).next("span").find(".addSepcDetailBtn").trigger("click");
                }
                var arrayDtl = list[m]["specDetails"];
                $(this).parent().parent().parent().find("input[name='specDetails']").each(function (n) {
                    $(this).val(arrayDtl[n].trim());
                })
            });

            //$("#modifySpecDetailSure").trigger("click");

        } else if (data.status === '2') {
            layer.msg(data.message);
        }
    });
}
		

		